package com.example.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.blog.base.CurrentAccount;
import com.example.blog.common.StatusEnums;
import com.example.blog.entity.Article;
import com.example.blog.entity.Comment;
import com.example.blog.entity.SysUser;
import com.example.blog.entity.dto.comment.AddCommentDTO;
import com.example.blog.entity.dto.comment.PageQueryDTO;
import com.example.blog.entity.vo.comment.CommentDetailInfoVO;
import com.example.blog.entity.vo.comment.CommentListVO;
import com.example.blog.mapper.CommentMapper;
import com.example.blog.service.ArticleService;
import com.example.blog.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blog.service.ReplyService;
import com.example.blog.service.SysUserService;
import com.example.blog.util.BeanUtils;
import com.example.blog.util.CurrentUserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author wlh
 * @since 2024-01-10
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {


    @Autowired
    private ReplyService replyService;


    @Autowired
    private ArticleService articleService;

    @Autowired
    @Lazy
    private SysUserService sysUserService;

    @Override
    public Long getNewCountByUser(Long userId) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Comment::getUserId, userId)
                .eq(Comment::getIsRead, StatusEnums.NOT_READ.getValue());

        return count(queryWrapper);
    }

    @Override
    public Long add(AddCommentDTO addCommentDTO) {

        Long articleId = addCommentDTO.getArticleId();

        Article article = articleService.getByIdNotNull(articleId);

        Comment comment = BeanUtils.copyProperties(addCommentDTO, Comment.class);
        comment.setIsRead(StatusEnums.NOT_READ.getValue());
        comment.setUserId(article.getCreatedBy());
        save(comment);

        return comment.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del(Long id) {
        removeById(id);
        replyService.delByComment(id);
    }

    @Override
    public Page<CommentDetailInfoVO> pageList(PageQueryDTO pageQueryDTO) {
        Page<Comment> commentPage = new Page<>(pageQueryDTO.getPageCurrent(), pageQueryDTO.getPageSize());

        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Comment::getArticleId, pageQueryDTO.getArticleId())
                .orderByDesc(Comment::getCreatedTime)
                ;

        page(commentPage, queryWrapper);

        List<Comment> records = commentPage.getRecords();
        if (records.isEmpty()) {
            return BeanUtils.copyPage(commentPage, CommentDetailInfoVO.class);
        }
        List<Long> collect = records.stream()
                .map(Comment::getUserId)
                .toList();

        Map<Long, SysUser> userMap = sysUserService.listByIds(collect)
                .stream()
                .collect(Collectors.toMap(SysUser::getId, Function.identity()));

        List<CommentDetailInfoVO> detailInfoVOList = records.stream()
                .map(comment -> {
                    CommentDetailInfoVO commentDetailInfoVO = BeanUtils.copyProperties(comment, CommentDetailInfoVO.class);
                    SysUser sysUser = userMap.get(comment.getUserId());
                    if (sysUser != null) {
                        commentDetailInfoVO.setNickname(sysUser.getNickname());
                        commentDetailInfoVO.setAvatar(sysUser.getAvatar());
                        commentDetailInfoVO.setUsername(sysUser.getUsername());
                    }
                    return commentDetailInfoVO;
                }).collect(Collectors.toList());
        Page<CommentDetailInfoVO> commentDetailInfoVOPage = BeanUtils.copyPage(commentPage, CommentDetailInfoVO.class);

        commentDetailInfoVOPage.setRecords(detailInfoVOList);

        return commentDetailInfoVOPage;
    }

    @Override
    public Page<CommentListVO> backPage(Integer current, Integer size, String content) {

        Page<CommentListVO> result = new Page<>(current, size);
        current = (current - 1) * size;

        long total = baseMapper.backPageTotal(content);

        if (total <= 0) {
            return result;
        }
        List<CommentListVO> list = baseMapper.backPageList(current, size, content);

        result.setTotal(total);

        result.setRecords(list);

        return new Page<CommentListVO>(current, size, total).setRecords(list);
    }


    @Override
    public List<CommentListVO> newComment() {

        CurrentAccount currentUser = CurrentUserUtils.currentUser();

        List<CommentListVO> commentListVOS = baseMapper.newComment(currentUser.getId());

        if (commentListVOS.isEmpty()) {
            return commentListVOS;
        }

        Set<Long> artIds = commentListVOS
                .stream()
                .map(CommentListVO::getArticleId)
                .collect(Collectors.toSet());

        List<Article> articles = articleService.listByIds(artIds);

        Map<Long, Article> articleMap = articles
                .stream()
                .collect(Collectors.toMap(Article::getId, Function.identity()));

        Set<Long> uids = commentListVOS
                .stream()
                .map(CommentListVO::getUserId)
                .collect(Collectors.toSet());

        List<SysUser> sysUsers = sysUserService.listByIds(uids);

        Map<Long, SysUser> userMap = sysUsers
                .stream()
                .collect(Collectors.toMap(SysUser::getId, Function.identity()));

        Map<Long, CommentListVO> commentMap = new HashMap<>();
        commentListVOS
                .forEach(commentListVO -> {
                    if (commentListVO.getArticleId() != null) {
                        // 一级评论
                        Article article = articleMap.get(commentListVO.getArticleId());
                        if (article != null) {
                            commentListVO.setArticleTitle(article.getTitle());
                            commentListVO.setSummary(article.getSummary());
                        }
                        SysUser sysUser = userMap.get(commentListVO.getUserId());
                        if (sysUser != null) {
                            commentListVO.setUsername(sysUser.getUsername());
                            commentListVO.setAvatar(sysUser.getAvatar());
                            commentListVO.setNickname(sysUser.getNickname());
                        }
                        commentMap.put(commentListVO.getId(), commentListVO);
                    }
                });

        commentListVOS.forEach(
                commentListVO -> {
                    if (commentListVO.getCommentId() != null) {
                        // 二级评论
                        CommentListVO commentListVO1 = commentMap.get(commentListVO.getCommentId());
                        if (commentListVO1 != null) {
                            commentListVO.setUserId(commentListVO1.getUserId());
                            commentListVO.setNickname(commentListVO1.getNickname());
                            commentListVO.setAvatar(commentListVO1.getAvatar());
                            commentListVO.setUsername(commentListVO1.getUsername());
                            commentListVO.setArticleTitle(commentListVO1.getArticleTitle());
                            commentListVO.setArticleId(commentListVO1.getArticleId());
                            commentListVO.setSummary(commentListVO1.getSummary());
                       }
                   }
                }
        );

        return commentListVOS;

    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void read() {
        LambdaUpdateWrapper<Comment> updateWrapper = new LambdaUpdateWrapper<>();

        CurrentAccount user = CurrentUserUtils.currentUser();

        updateWrapper.eq(Comment::getIsRead, StatusEnums.NOT_READ.getValue())
                .eq(Comment::getUserId, user.getId())
                .set(Comment::getIsRead, StatusEnums.READ.getValue())
                ;

        update(updateWrapper);

        replyService.read();
    }
}
